<script setup lang="ts">
import { ref, reactive, onMounted, h, nextTick, watch } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElButton,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElInput,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElCard,
  ElDivider,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElOptionGroup,
  ElRow,
  ElCol,
} from "element-plus";
import {
  Refresh,
  Plus,
  View,
  Edit,
  Delete,
  VideoPlay,
  Star,
  ArrowDown,
} from "@element-plus/icons-vue";
import {
  getTemplateList,
  getTemplateDetail,
  createTemplate,
  createTaskFromTemplate,
  recommendTemplates,
  getTemplateStatistics,
  getScenarioList,
} from "../servers";

const props = defineProps<{
  task: string;
}>();

// 威胁类型图标映射
const threatTypeIcons = {
  sql_injection: "💉", // SQL注入
  command_injection: "⚡", // 命令注入
  code_execution: "🔥", // 代码执行
  deserialization: "📦", // 反序列化
  file_upload: "📤", // 文件上传
  file_inclusion: "📂", // 文件包含
  ssrf: "🌐", // SSRF
  xxe: "📄", // XXE
  template_injection: "🎨", // 模板注入
  xss: "🚨", // XSS
  authentication_bypass: "🔓", // 认证绕过
  information_disclosure: "🔍", // 信息泄露
};

// 攻击分类颜色方案
const categoryColors = {
  rce: "#E53935", // 红色 - 远程代码执行
  web_attack: "#FB8C00", // 橙色 - Web攻击
  authentication: "#FDD835", // 黄色 - 认证授权
  file_operation: "#7CB342", // 绿色 - 文件操作
  database: "#00ACC1", // 青色 - 数据库
  api_security: "#5E35B1", // 紫色 - API安全
  cloud_native: "#3949AB", // 蓝色 - 云原生
};

// 严重程度配置
const severityConfig = {
  critical: {
    color: "#F44336",
    label: "严重",
    badge: "danger",
  },
  high: {
    color: "#FF9800",
    label: "高危",
    badge: "warning",
  },
  medium: {
    color: "#FFC107",
    label: "中危",
    badge: "info",
  },
  low: {
    color: "#4CAF50",
    label: "低危",
    badge: "success",
  },
};

// 预设模板方案
const presetTemplates = [
  {
    name: "Web应用快速测试",
    category: "Web",
    description: "针对Web应用的快速安全扫描",
    scenarioIds: [1, 2, 7, 14, 16, 22], // SQL注入 + XSS + 文件读取 + SSRF + XSS
    icon: "🌐",
  },
  {
    name: "Java应用深度测试",
    category: "Java",
    description: "针对Java技术栈的全面测试",
    scenarioIds: [9, 10, 11, 12, 21], // OGNL + Log4j + Fastjson + Shiro + Thymeleaf
    icon: "☕",
  },
  {
    name: "红队渗透测试",
    category: "红队",
    description: "模拟APT攻击的综合测试",
    scenarioIds: [1, 4, 5, 10, 13, 15, 20, 23], // 高危漏洞组合
    icon: "🔴",
  },
  {
    name: "API安全测试",
    category: "API",
    description: "针对RESTful API的安全测试",
    scenarioIds: [1, 2, 3, 16, 17, 24], // SQL注入 + SSRF + JWT
    icon: "🔌",
  },
  {
    name: "等保三级测试",
    category: "合规",
    description: "满足等保三级安全测试要求",
    scenarioIds: [1, 2, 4, 5, 13, 22, 23, 25], // 覆盖等保要求的常见漏洞
    icon: "🛡️",
  },
];

const loading = ref(false);
const templateList = ref<any[]>([]);
const searchFormRef = ref<DynamicFormInstance>();

// 统计信息
const statistics = ref({
  total: 0,
  system: 0,
  custom: 0,
  usage_count: 0,
});

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const searchForm = reactive({
  is_system: undefined as boolean | undefined,
});

const searchConfig: FormItemConfig[] = [
  {
    key: "is_system",
    name: "模板类型",
    type: "select",
    labelWidth: "80px",
    placeholder: "选择模板类型",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: undefined },
        { label: "系统模板", value: true },
        { label: "自定义模板", value: false },
      ],
    },
  },
];

const columns = ref<TableColumn[]>([
  {
    label: "模板名称",
    prop: "template_name",
    show: true,
    minWidth: 180,
    render: (row) => {
      return h(
        "div",
        { style: "display: flex; align-items: center; gap: 8px" },
        [
          h("span", { style: "font-size: 16px" }, row.icon || "📋"),
          h("div", {}, [
            h("div", { style: "font-weight: bold" }, row.template_name),
            // h(
            //   "div",
            //   { style: "font-size: 12px; color: #666" },
            //   row.template_name_en || ""
            // ),
          ]),
        ]
      );
    },
  },
  {
    label: "分类",
    prop: "category",
    show: true,
    render: (row) => {
      const color = row.color || "#409EFF";
      return h(
        ElTag,
        {
          style: `background-color: ${color}; color: white; border: none;`,
        },
        row.category || "未分类"
      );
    },
  },
  {
    label: "类型",
    prop: "is_system",
    show: true,
    render: (row) => {
      const typeMap: Record<string, any> = {
        true: { text: "系统", type: "primary" },
        false: { text: "自定义", type: "success" },
      };
      const typeInfo = typeMap[String(row.is_system)] || {
        text: row.is_system ? "系统" : "自定义",
        type: row.is_system ? "primary" : "success",
      };
      return h(ElTag, { type: typeInfo.type, size: "small" }, typeInfo.text);
    },
  },
  {
    label: "风险等级",
    prop: "risk_level",
    show: true,
    render: (row) => {
      const riskConfig: Record<string, any> = {
        critical: { text: "严重", type: "danger" },
        high: { text: "高危", type: "warning" },
        medium: { text: "中危", type: "info" },
        low: { text: "低危", type: "success" },
      };
      const riskInfo = riskConfig[row.risk_level] || {
        text: row.risk_level || "未知",
        type: "info",
      };
      return h(ElTag, { type: riskInfo.type, size: "small" }, riskInfo.text);
    },
  },
  {
    label: "场景数量",
    prop: "total_scenarios",
    show: true,
    render: (row) => {
      const count = row.total_scenarios || row.scenario_count || 0;
      return h(
        "span",
        { style: "font-weight: bold; color: #409EFF" },
        `${count}个`
      );
    },
  },
  {
    label: "预计时长",
    prop: "estimated_duration",
    show: true,
    render: (row) => {
      const duration = row.estimated_duration;
      return h("span", {}, duration ? `${duration}分钟` : "-");
    },
  },
  // {
  //   label: "成功率",
  //   prop: "success_rate",
  //   width: 100,
  //   show: true,
  //   render: (row) => {
  //     const rate = (row.success_rate || 0) * 100;
  //     const color = rate >= 80 ? "#67C23A" : rate >= 60 ? "#E6A23C" : "#F56C6C";
  //     return h(
  //       "span",
  //       { style: `color: ${color}; font-weight: bold` },
  //       `${rate.toFixed(1)}%`
  //     );
  //   },
  // },
  {
    label: "使用次数",
    prop: "usage_count",
    width: 100,
    show: true,
    render: (row) => {
      const count = row.usage_count || 0;
      return h(
        "span",
        { style: "color: #909399; font-weight: 500" },
        `${count}次`
      );
    },
  },
  {
    label: "创建时间",
    prop: "created_at",
    width: 120,
    show: true,
    render: (row) => {
      const date = row.created_at;
      if (!date) return h("span", { style: "color: #C0C4CC" }, "-");
      const dateObj = new Date(date);
      const formatted = dateObj.toLocaleDateString("zh-CN", {
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      });
      return h("span", { style: "font-size: 12px; color: #666" }, formatted);
    },
  },
  // {
  //   label: "标签",
  //   prop: "tags",
  //   width: 200,
  //   show: true,
  //   render: (row) => {
  //     const tags = row.tags || [];
  //     if (tags.length === 0)
  //       return h("span", { style: "color: #C0C4CC" }, "无");

  //     return h(
  //       "div",
  //       { style: "display: flex; flex-wrap: wrap; gap: 4px" },
  //       tags
  //         .slice(0, 3)
  //         .map((tag: string) =>
  //           h(
  //             ElTag,
  //             {
  //               size: "small",
  //               type: "info",
  //               style: "margin: 2px 0",
  //             },
  //             tag
  //           )
  //         )
  //         .concat(
  //           tags.length > 3
  //             ? [
  //                 h(
  //                   ElTag,
  //                   {
  //                     size: "small",
  //                     type: "info",
  //                     style: "margin: 2px 0",
  //                   },
  //                   `+${tags.length - 3}`
  //                 ),
  //               ]
  //             : []
  //         )
  //     );
  //   },
  // },
  {
    label: "操作",
    prop: "action",
    width: 200,
    fixed: "right",
    show: true,
    slot: "action",
  },
]);

const showDetailDialog = ref(false);
const showCreateDialog = ref(false);
const showCreateTaskDialog = ref(false);
const showRecommendDialog = ref(false);
const templateDetail = ref<any>(null);
const loadingDetail = ref(false);
const formRef = ref<any>();

const formData = reactive({
  template_name: "",
  category: "",
  scenario_ids: [] as number[],
});

// 场景统计信息
const scenarioStats = ref({
  total: 0,
  bySeverity: {} as Record<string, number>,
  byThreatType: {} as Record<string, number>,
  byCategory: {} as Record<string, number>,
});

// 表单验证规则
const formRules = {
  template_name: [
    { required: true, message: "请输入模板名称", trigger: "blur" },
  ],
  category: [{ required: true, message: "请输入模板分类", trigger: "blur" }],
  scenario_ids: [
    { required: true, message: "请选择至少一个场景", trigger: "change" },
  ],
};

const createTaskFormData = reactive({
  template_id: undefined as number | undefined,
  target_url: "",
  task_name: "",
});

const recommendFormData = reactive({
  target_url: "",
  target_type: "web", // 默认web
});

const addFormConfig: FormItemConfig[] = [
  {
    key: "template_name",
    name: "模板名称",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入模板名称",
    rules: [{ required: true, message: "请输入模板名称" }],
  },
  {
    key: "category",
    name: "模板分类",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入模板分类",
    rules: [{ required: true, message: "请输入模板分类" }],
  },
  {
    key: "scenario_ids",
    name: "包含场景",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择包含的场景",
    rules: [{ required: true, message: "请选择至少一个场景" }],
    params: {
      multiple: true,
      options: [], // 这里需要从场景列表获取
    },
  },
];

const createTaskFormConfig: FormItemConfig[] = [
  {
    key: "target_url",
    name: "目标URL",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入目标URL",
    rules: [{ required: true, message: "请输入目标URL" }],
  },
  {
    key: "task_name",
    name: "任务名称",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入任务名称",
  },
];

const recommendFormConfig: FormItemConfig[] = [
  {
    key: "target_url",
    name: "目标URL",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入目标URL",
  },
  {
    key: "target_type",
    name: "目标类型",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择目标类型",
    params: {
      clearable: false,
      options: [
        { label: "Web应用", value: "web" },
        { label: "API接口", value: "api" },
        { label: "Java应用", value: "java" },
      ],
    },
  },
];

const fetchTemplateList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
    };

    // 根据MD文档，只传is_system参数
    if (searchForm.is_system !== undefined) {
      params.is_system = searchForm.is_system;
    }

    const { data } = await getTemplateList(params);

    templateList.value = data?.templates || [];
    pagination.total = data?.total || 0;
    fetchStatistics();
  } catch (error) {
    ElMessage.error("获取模板列表失败");
  } finally {
    loading.value = false;
  }
};

const fetchStatistics = async () => {
  try {
    const { data } = await getTemplateStatistics();
    if (data) {
      // 计算系统模板和自定义模板数量
      const systemCount =
        data.template_stats?.filter(
          (item: any) =>
            item.template_code?.startsWith("TEMPLATE_") &&
            !item.template_code?.includes("CUSTOM")
        ).length || 0;

      const customCount =
        data.template_stats?.filter((item: any) =>
          item.template_code?.includes("CUSTOM")
        ).length || 0;

      // 计算总使用次数
      const totalUsage =
        data.template_stats?.reduce(
          (sum: number, item: any) => sum + (item.usage_count || 0),
          0
        ) || 0;

      statistics.value = {
        total: data.total_templates || 0,
        system: systemCount,
        custom: customCount,
        usage_count: totalUsage,
      };
    }
  } catch (error) {
    console.error("获取统计信息失败:", error);
  }
};

const fetchScenarioList = async () => {
  try {
    const { data } = await getScenarioList({
      page_size: 1000,
      is_active: true,
    });
    // 根据API返回格式处理数据
    const scenarios = data?.scenarios || [];

    // 按攻击分类分组场景
    const groupedScenarios = scenarios.reduce((acc: any, scenario: any) => {
      const category = scenario.attack_category || "other";
      if (!acc[category]) {
        acc[category] = [];
      }
      acc[category].push(scenario);
      return acc;
    }, {});

    // 创建分组选项
    const groupedOptions = Object.keys(groupedScenarios).map((category) => {
      const categoryName =
        {
          rce: "🔥 远程代码执行 (RCE)",
          web_attack: "🌐 Web攻击",
          authentication: "🔓 认证授权",
          file_operation: "📁 文件操作",
          other: "📋 其他",
        }[category] || `📋 ${category}`;

      return {
        label: categoryName,
        options: groupedScenarios[category].map((s: any) => ({
          label: `${threatTypeIcons[s.threat_type] || "🔍"} ${
            s.scenario_name
          } (${s.scenario_code})`,
          value: s.id,
          severity: s.severity,
          threatType: s.threat_type,
          attackCategory: s.attack_category,
          disabled: false,
        })),
      };
    });

    addFormConfig[2].params!.options = groupedOptions;
  } catch (error) {
    console.error("获取场景列表失败:", error);
    ElMessage.error("获取场景列表失败");
  }
};

const handleSearch = (value: any) => {
  Object.assign(searchForm, value);
  pagination.currentPage = 1;
  fetchTemplateList();
};

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  Object.assign(searchForm, {
    is_system: undefined,
  });
  pagination.currentPage = 1;
  fetchTemplateList();
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchTemplateList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchTemplateList();
};

const handleViewDetail = async (row: any) => {
  loadingDetail.value = true;
  try {
    const { data } = await getTemplateDetail({
      template_code: row.template_code,
    });
    templateDetail.value = data;
    showDetailDialog.value = true;
  } catch (error) {
    ElMessage.error("获取模板详情失败");
  } finally {
    loadingDetail.value = false;
  }
};

const handleCreateTask = (row: any) => {
  Object.assign(createTaskFormData, {
    template_id: row.template_code || row.template_code,
    target_url: "",
    task_name: "",
  });
  showCreateTaskDialog.value = true;
};

const handleSubmitCreateTask = async (values: any) => {
  try {
    await createTaskFromTemplate({
      template_code: createTaskFormData.template_id,
      ...values,
    });
    ElMessage.success("任务创建成功");
    showCreateTaskDialog.value = false;
  } catch (error) {
    ElMessage.error("任务创建失败");
  }
};

const handleCloseCreateTaskDialog = () => {
  showCreateTaskDialog.value = false;
  formRef.value?.resetFields();
  Object.assign(createTaskFormData, {
    template_id: undefined,
    target_url: "",
    task_name: "",
  });
};

const handleAdd = () => {
  Object.assign(formData, {
    template_name: "",
    category: "",
    scenario_ids: [],
  });
  showCreateDialog.value = true;
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

const handlePresetTemplate = (preset: any) => {
  showCreateDialog.value = true;
  nextTick(() => {
    // 先重置表单，然后设置预设数据
    formRef.value?.resetFields();
    nextTick(() => {
      Object.assign(formData, {
        template_name: preset.name,
        category: preset.category,
        scenario_ids: preset.scenarioIds,
      });
    });
  });
};

// 计算场景统计信息
const calculateScenarioStats = (scenarioIds: number[]) => {
  if (!scenarioIds.length) {
    scenarioStats.value = {
      total: 0,
      bySeverity: {},
      byThreatType: {},
      byCategory: {},
    };
    return;
  }

  // 获取所有场景数据
  const allScenarios =
    addFormConfig[2].params?.options?.flatMap(
      (group: any) => group.options || []
    ) || [];
  const selectedScenarios = allScenarios.filter((s: any) =>
    scenarioIds.includes(s.value)
  );

  const stats = {
    total: selectedScenarios.length,
    bySeverity: {} as Record<string, number>,
    byThreatType: {} as Record<string, number>,
    byCategory: {} as Record<string, number>,
  };

  selectedScenarios.forEach((scenario: any) => {
    // 按严重程度统计
    stats.bySeverity[scenario.severity] =
      (stats.bySeverity[scenario.severity] || 0) + 1;
    // 按威胁类型统计
    stats.byThreatType[scenario.threatType] =
      (stats.byThreatType[scenario.threatType] || 0) + 1;
    // 按攻击分类统计
    stats.byCategory[scenario.attackCategory] =
      (stats.byCategory[scenario.attackCategory] || 0) + 1;
  });

  scenarioStats.value = stats;
};

const handleCloseCreateDialog = () => {
  showCreateDialog.value = false;
  formRef.value?.resetFields();
  Object.assign(formData, {
    template_name: "",
    category: "",
    scenario_ids: [],
  });
};

const handleSubmitForm = async () => {
  try {
    // 验证表单
    if (formRef.value) {
      await formRef.value.validate();
    }

    await createTemplate(formData);
    ElMessage.success("模板创建成功");
    showCreateDialog.value = false;
    fetchTemplateList();
    fetchStatistics();
  } catch (error) {
    console.error("模板创建失败:", error);
    ElMessage.error("模板创建失败");
  }
};

const handleRecommend = () => {
  console.log("推荐模板提交数据:", recommendFormData);
  Object.assign(recommendFormData, {
    target_type: "web", // 默认web
  });
  showRecommendDialog.value = true;
};

const handleSubmitRecommend = async (values: any) => {
  console.log("推荐模板提交数据:", values);
  try {
    const { data } = await recommendTemplates(values);
    ElMessage.success("推荐模板获取成功");
    showRecommendDialog.value = false;
    // 这里可以展示推荐结果
    fetchTemplateList();
    fetchStatistics();
  } catch (error) {
    ElMessage.error("获取推荐模板失败");
  }
};

const handleCloseRecommendDialog = () => {
  showRecommendDialog.value = false;
  formRef.value?.resetFields();
  Object.assign(recommendFormData, {
    target_url: "",
    target_type: "web", // 默认web
  });
};

// 监听场景选择变化
watch(
  () => formData.scenario_ids,
  (newIds) => {
    calculateScenarioStats(newIds);
  },
  { deep: true }
);

onMounted(() => {
  fetchTemplateList();
  fetchStatistics();
  fetchScenarioList(); // 初始化时获取场景列表
});
</script>

<template>
  <div>
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchForm"
          :form-config="searchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <el-descriptions title="模板统计" :column="4" border>
        <el-descriptions-item label="总模板数">
          <el-tag type="info" size="large">{{ statistics.total }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="系统模板">
          <el-tag type="info" size="large">{{ statistics.system }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="自定义模板">
          <el-tag type="success" size="large">{{ statistics.custom }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="使用次数">
          <el-tag type="info" size="large">{{ statistics.usage_count }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <DynamicTable
        :columns="columns"
        :data="templateList"
        :loading="loading"
        :pagination="pagination"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleAdd"> 创建模板 </el-button>
          <el-button type="success" @click="handleRecommend">
            推荐模板
          </el-button>
        </template>

        <template #action="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
          <el-button type="success" size="small" @click="handleCreateTask(row)">
            创建任务
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 模板详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="模板详情" width="900px">
      <el-descriptions
        v-if="templateDetail"
        :column="2"
        border
        v-loading="loadingDetail"
      >
        <el-descriptions-item label="模板代码">{{
          templateDetail.template_code
        }}</el-descriptions-item>
        <el-descriptions-item label="模板名称">{{
          templateDetail.template_name
        }}</el-descriptions-item>
        <el-descriptions-item label="英文名称">{{
          templateDetail.template_name_en || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="模板类型">
          <el-tag :type="templateDetail.is_system ? 'info' : 'success'">
            {{ templateDetail.is_system ? "系统" : "自定义" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="分类">
          <el-tag
            :style="`background-color: ${
              templateDetail.color || '#409EFF'
            }; color: white; border: none;`"
          >
            {{ templateDetail.category || "无" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="风险等级">
          <el-tag
            :type="
              templateDetail.risk_level === 'critical'
                ? 'danger'
                : templateDetail.risk_level === 'high'
                ? 'warning'
                : templateDetail.risk_level === 'medium'
                ? 'info'
                : 'success'
            "
          >
            {{
              templateDetail.risk_level === "critical"
                ? "严重"
                : templateDetail.risk_level === "high"
                ? "高危"
                : templateDetail.risk_level === "medium"
                ? "中危"
                : templateDetail.risk_level === "low"
                ? "低危"
                : templateDetail.risk_level || "未知"
            }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="场景数量">
          <el-tag type="info"
            >{{
              templateDetail.total_scenarios ||
              templateDetail.scenario_count ||
              0
            }}个</el-tag
          >
        </el-descriptions-item>
        <el-descriptions-item label="预计时长">
          <el-tag type="info"
            >{{ templateDetail.estimated_duration || "无" }}分钟</el-tag
          >
        </el-descriptions-item>
        <el-descriptions-item label="成功率">
          <el-tag
            :type="
              (templateDetail.success_rate || 0) >= 0.8
                ? 'success'
                : (templateDetail.success_rate || 0) >= 0.6
                ? 'warning'
                : 'danger'
            "
          >
            {{ ((templateDetail.success_rate || 0) * 100).toFixed(1) }}%
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="使用次数">
          <el-tag type="info">{{ templateDetail.usage_count || 0 }}次</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="目标环境">
          <el-tag type="info">{{
            templateDetail.target_environment || "无"
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建者">{{
          templateDetail.created_by || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          templateDetail.created_at || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          templateDetail.updated_at || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ templateDetail.description || "无" }}
        </el-descriptions-item>
        <el-descriptions-item label="合规标准" :span="2">
          <template
            v-if="
              templateDetail.compliance_standards &&
              templateDetail.compliance_standards.length > 0
            "
          >
            <el-tag
              v-for="standard in templateDetail.compliance_standards"
              :key="standard"
              size="small"
              type="success"
              style="margin-right: 4px"
            >
              {{ standard }}
            </el-tag>
          </template>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="标签" :span="2">
          <template
            v-if="templateDetail.tags && templateDetail.tags.length > 0"
          >
            <el-tag
              v-for="tag in templateDetail.tags"
              :key="tag"
              size="small"
              type="info"
              style="margin-right: 4px"
            >
              {{ tag }}
            </el-tag>
          </template>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="任务配置" :span="2">
          <template v-if="templateDetail.task_config">
            <div style="display: flex; flex-wrap: wrap; gap: 8px">
              <el-tag size="small" type="info">
                并发数: {{ templateDetail.task_config.concurrent || "N/A" }}
              </el-tag>
              <el-tag size="small" type="info">
                超时: {{ templateDetail.task_config.timeout || "N/A" }}s
              </el-tag>
              <el-tag
                size="small"
                :type="
                  templateDetail.task_config.enable_advanced_payloads
                    ? 'success'
                    : 'info'
                "
              >
                高级载荷:
                {{
                  templateDetail.task_config.enable_advanced_payloads
                    ? "启用"
                    : "禁用"
                }}
              </el-tag>
              <el-tag
                size="small"
                :type="
                  templateDetail.task_config.enable_waf_bypass
                    ? 'success'
                    : 'info'
                "
              >
                WAF绕过:
                {{
                  templateDetail.task_config.enable_waf_bypass ? "启用" : "禁用"
                }}
              </el-tag>
            </div>
          </template>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="包含场景" :span="2">
          <el-input
            :value="
              templateDetail.scenarios
                ?.map((s) => s.scenario_name)
                .join(', ') || '无'
            "
            type="textarea"
            :rows="3"
            readonly
          />
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 创建模板对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建模板"
      width="1000px"
      @close="handleCloseCreateDialog"
    >
      <div style="margin-bottom: 20px">
        <h4>💡 预设模板方案</h4>
        <div
          style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px"
        >
          <el-card
            v-for="preset in presetTemplates"
            :key="preset.name"
            shadow="hover"
            style="width: 180px; cursor: pointer"
            @click="handlePresetTemplate(preset)"
          >
            <div style="text-align: center">
              <div style="font-size: 24px; margin-bottom: 8px">
                {{ preset.icon }}
              </div>
              <div style="font-weight: bold; margin-bottom: 4px">
                {{ preset.name }}
              </div>
              <el-tag size="small" type="info">{{ preset.category }}</el-tag>
              <div style="font-size: 12px; color: #666; margin-top: 4px">
                {{ preset.description }}
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <el-divider />

      <!-- 场景统计信息 -->
      <div v-if="scenarioStats.total > 0" style="margin-bottom: 20px">
        <div
          class="title"
          style="font-size: 16px; font-weight: bold; margin-bottom: 10px"
        >
          📊 已选场景统计
        </div>
        <el-descriptions :column="4" border size="small">
          <el-descriptions-item label="总场景数">
            <el-tag type="info" size="small">{{ scenarioStats.total }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="严重程度分布">
            <div
              style="display: flex; gap: 8px; flex-wrap: wrap; margin-top: 5px"
            >
              <el-tag
                v-for="(count, severity) in scenarioStats.bySeverity"
                :key="severity"
                :type="(severityConfig[severity as keyof typeof severityConfig]?.badge as any) || 'info'"
                size="small"
              >
                {{
                  severityConfig[severity as keyof typeof severityConfig]
                    ?.label || severity
                }}: {{ count }}
              </el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="威胁类型分布" :span="2">
            <div
              style="display: flex; gap: 8px; flex-wrap: wrap; margin-top: 5px"
            >
              <el-tag
                v-for="(count, threatType) in scenarioStats.byThreatType"
                :key="threatType"
                type="info"
                size="small"
              >
                {{
                  threatTypeIcons[threatType as keyof typeof threatTypeIcons] ||
                  "🔍"
                }}
                {{ threatType }}: {{ count }}
              </el-tag>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 自定义表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        :gutter="16"
      >
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="模板名称" prop="template_name" required>
              <el-input
                v-model="formData.template_name"
                placeholder="请输入模板名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板分类" prop="category" required>
              <el-input
                v-model="formData.category"
                placeholder="请输入模板分类"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="包含场景" prop="scenario_ids" required>
              <el-select
                v-model="formData.scenario_ids"
                multiple
                filterable
                placeholder="选择包含的场景"
                style="width: 100%"
              >
                <el-option-group
                  v-for="group in addFormConfig[2].params?.options"
                  :key="group.label"
                  :label="group.label"
                >
                  <el-option
                    v-for="option in group.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                    :disabled="option.disabled"
                  >
                    <span style="float: left">{{ option.label }}</span>
                    <span
                      v-if="option.severity"
                      style="float: right; color: #8492a6; font-size: 13px"
                    >
                      {{
                        severityConfig[
                          option.severity as keyof typeof severityConfig
                        ]?.label || option.severity
                      }}
                    </span>
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button @click="handleCloseCreateDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmitForm">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 创建任务对话框 -->
    <el-dialog
      v-model="showCreateTaskDialog"
      title="基于模板创建任务"
      width="600px"
      @close="handleCloseCreateTaskDialog"
    >
      <DynamicForm
        ref="formRef"
        v-model="createTaskFormData"
        :form-config="createTaskFormConfig"
        :gutter="16"
        type="submit"
        @submit="handleSubmitCreateTask"
        @cancel="handleCloseCreateTaskDialog"
      />
    </el-dialog>

    <!-- 推荐模板对话框 -->
    <el-dialog
      v-model="showRecommendDialog"
      title="推荐模板"
      width="600px"
      @close="handleCloseRecommendDialog"
    >
      <DynamicForm
        ref="formRef"
        v-model="recommendFormData"
        :form-config="recommendFormConfig"
        :gutter="16"
        type="submit"
        @submit="handleSubmitRecommend"
        @cancel="handleCloseRecommendDialog"
      />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>
